import java.awt.BorderLayout;

import javafx.collections.ObservableList;
import javafx.embed.swing.JFXPanel;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

import javax.swing.JFrame;
import javax.swing.JPanel;

import com.sun.javafx.application.PlatformImpl;

public class Authorization extends JPanel {

	private static final long serialVersionUID = 1L;
	private static final int WIDTH = 819;
	private static final int HEIGHT = 620;
	private static final String CONNECTION_URL = "http://api.vk.com/oauth/authorize?client_id=2804045&redirect_uri=http://api.vk.com/blank.html/callback&response_type=code&scope=wall";
	private static final String VKONTAKTE = "http://vk.com";

	private static JFrame frame;
	private Stage stage;
	private WebView browser;
	private JFXPanel jfxPanel;
	private WebEngine webEngine;
	private static String Code = null;
	private static String Message = null;

	public Authorization(String aMessage) {

		Message = aMessage;

		frame = new JFrame();
		
		frame.setResizable(false);

		frame.setSize(WIDTH, HEIGHT);
		// frame.setMinimumSize(new Dimension(WIDTH, HEIGHT));
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.setVisible(true);

		jfxPanel = new JFXPanel();
		createScene();

		frame.setLayout(new BorderLayout());
		frame.add(jfxPanel, BorderLayout.CENTER);

	}

	private void createScene() {
		PlatformImpl.startup(new Runnable() {
			public void run() {

				stage = new Stage();

				stage.setResizable(true);

				Group root = new Group();
				Scene scene = new Scene(root, 80, 20);
				stage.setScene(scene);

				browser = new WebView();

				webEngine = browser.getEngine();

				webEngine.load(CONNECTION_URL);

				browser.setOnMouseMoved(new EventHandler<Event>() {

					public void handle(Event arg0) {

						if (webEngine.getLocation().indexOf("code=") != -1) {

							String URL = webEngine.getLocation();
							setCode(URL.substring(URL.indexOf("code") + 5));
							new Share(getCode(), Message);

							webEngine.load(VKONTAKTE);

						}
					}

				});

				ObservableList<Node> children = root.getChildren();
				children.add(browser);

				jfxPanel.setScene(scene);
			}
		});
	}

	private static void setCode(String s) {
		Code = s;
	}

	private static String getCode() {
		return Code;
	}

}